package com.lu.admin.service.impl;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.admin.mapper.AdUserMapper;
import com.lu.admin.service.AdUserService;
import com.lu.model.admin.dto.AdUserDto;
import com.lu.model.admin.pojo.AdUser;
import com.lu.model.common.dtos.ResponseResult;
import com.lu.model.common.enums.AppHttpCodeEnum;
import com.lu.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Slf4j
@Service
@Transactional
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    /**
     * 登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        //参数判断
        if (StringUtils.isBlank(dto.getName()) ||StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查找用户是否存在
        AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }
        //对比密码
        String salt = adUser.getSalt();
        String userPassword = adUser.getPassword();
        String dtoPassword = dto.getPassword();
        dtoPassword = DigestUtils.md5DigestAsHex((dtoPassword + salt).getBytes());
        if (!dtoPassword.equals(userPassword)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //签发令牌
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
        adUser.setSalt("");
        adUser.setPassword("");
        map.put("user", adUser);

        return ResponseResult.okResult(map);
    }
}
